<script setup>
import { ref, watchEffect, computed } from 'vue'
import IconSvg from './IconSvg.vue'

// 定义组件属性及默认值
const props = defineProps({
  // 总条数
  total: {
    type: Number,
    default: 0
  },
  // 每页条数
  pageSize: {
    type: Number,
    default: 10
  }
})

// 双向绑定当前页码（默认第1页）
const current = defineModel('current', { default: 1 })

// 定义页码变化事件
const emit = defineEmits(['onPageChange'])

// 总页数
const pageCount = ref(1)

// 监听总条数和每页条数变化，更新总页数
watchEffect(() => {
  pageCount.value = Math.ceil((props.total * 1.0) / props.pageSize)
})

// 计算当前页的起始和结束条数
const start = (current.value - 1) * props.pageSize + 1
const end = Math.min(current.value * props.pageSize, props.total)

// 处理页码变化
function handlePageChange(page) {
  // 边界校验：页码不能小于1或大于总页数
  if (page < 1 || page > pageCount.value) return
  // 发射事件通知父组件
  emit('onPageChange', page)
  // 更新当前页码
  current.value = page
}

// 计算需要显示的页码列表（处理省略号逻辑）
const showPages = computed(() => {
  const pages = []
  const totalPages = pageCount.value
  const curr = current.value

  if (totalPages <= 6) {
    // 总页数≤6时，全部显示
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i)
    }
  } else {
    // 总页数>6时，显示首尾页+当前页附近页码+省略号
    if (curr <= 3) {
      pages.push(1, 2, 3, 4, '...', totalPages)
    } else if (curr >= totalPages - 2) {
      pages.push(1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages)
    } else {
      pages.push(1, '...', curr - 1, curr, curr + 1, '...', totalPages)
    }
  }

  return pages
})
</script>

<template>
  <div class="flex text-[#000000e0]">
    <ul class="list-none flex items-center py-[6px] px-[0px] font-medium">
      <!-- 上一页 -->
      <li title="上一页">
        <a @click="handlePageChange(current - 1)">
          <IconSvg class="w-full h-full text-[#86909c]" name="left" />
        </a>
      </li>

      <!-- 页码列表 -->
      <li v-for="(i, index) in showPages" :key="index" :class="{ active: i === current }">
        <span v-if="i === '...'">{{ i }}</span>
        <a v-else @click="handlePageChange(i)">{{ i }}</a>
      </li>

      <!-- 下一页 -->
      <li title="下一页">
        <a @click="handlePageChange(current + 1)">
          <IconSvg class="w-full h-full text-[#86909c]" name="right" />
        </a>
      </li>
    </ul>
  </div>
</template>

<style scoped>
ul {
  list-style: none;
  display: flex;
  align-items: center;
  padding: 6px 0px;
}

li {
  height: 32px;
  min-width: 32px;
  width: 32px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
  border-radius: 6px;
  margin-right: 10px;
}

li:hover {
  background-color: rgba(0, 0, 0, 0.08);
}

li a {
  display: block;
  height: 100%;
  width: 100%;
  text-align: center;
}

li span {
  display: block;
  width: 100%;
  text-align: center;
  color: #999;
  cursor: default;
}

/* 当前页码样式 */
.active {
  border: 1px solid #457af7;
}

.active a {
  color: #457af7;
}
</style>